package org.onepiece.admin.common.config.advice;

import lombok.AllArgsConstructor;
import org.onepiece.admin.common.utils.CommonResult;
import org.onepiece.admin.common.constant.CommonConstants;
import org.onepiece.admin.common.config.nacos.OnepieceConfig;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zhujianke@gaodun.com
 * @since 2023/2/15 17:35
 */
@AllArgsConstructor
@RestControllerAdvice(basePackages = {CommonConstants.COMMON_RESPONSE_BODY_ADVICE_PACKAGE})
public class CommonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final OnepieceConfig onepieceConfig;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return onepieceConfig.getEnableResponseBodyAdvice();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return body instanceof CommonResult ? body : CommonResult.ok(body);
    }
}
